package apis

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	modelsadmin "tuowei.com/app/admin/models"
	serviceadmin "tuowei.com/app/admin/service"
	dtoadmin "tuowei.com/app/admin/service/dto"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/common/global"
	"tuowei.com/pkg/xlog"
)

type ApiShoppingCart struct {
	api.Api
}

func (e ApiShoppingCart) GetPages(c *gin.Context) {
	s := service.SysShoppingCart{}
	req := dto.SysShoppingCartGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(c)
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	var count int64
	list := make([]models.SysShoppingCart, 0)

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	xlog.Infof("ApiShoppingCart GetPages list:%+v", list)
	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e ApiShoppingCart) Insert(c *gin.Context) {
	s := service.SysShoppingCart{}
	req := dto.SysShoppingCartInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(c)
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	switch req.OrderType {
	case "MaterialOrder":
		//判断BuyerId，MaterialOnlineId，OrderType 已存在，修改
		type Inum struct {
			Id  int `json:"id"`
			Num int `json:"num"`
		}
		inum := &Inum{}
		err = e.Orm.Table("sys_shopping_cart").Select("id", "num").Where("deleted_at is null and buyer_id=? and material_online_id=? and order_type=?", req.BuyerId, req.MaterialOnlineId, req.OrderType).Scan(&inum).Error
		if err != nil {
			e.Logger.Error("db error:", err)
		}
		if inum.Num >= 1 { //存在,更新
			err := e.Orm.Table("sys_shopping_cart").Where("id=?", inum.Id).Update("num", inum.Num+1).Error
			if err != nil {
				e.Logger.Error("db error:", err)
				return
			}

		} else {
			//新增
			var object modelsadmin.SysMaterial
			sa := serviceadmin.SysMaterial{}
			sa.Orm = s.Orm
			reqa := dtoadmin.SysMaterialById{}
			reqa.Id = req.MaterialOnlineId
			//数据权限检查
			p := actions.GetPermissionFromContext(c)
			err = sa.Get(&reqa, p, &object)
			if err != nil {
				e.Error(http.StatusUnprocessableEntity, err, "查询失败")
				return
			}
			err = s.Insert(&req, object.Name, object.Subject, object.Introduction, "MaterialOrder", object.Cover, float64(object.Price))
			if err != nil {
				e.Logger.Error(err)
				e.Error(500, err, err.Error())
				return
			}
		}

	case "OnlineOrder", "LiveOrder":
		//判断BuyerId，MaterialOnlineId，OrderType 已存在，修改
		type Inum struct {
			Id  int `json:"id"`
			Num int `json:"num"`
		}
		inum := &Inum{}
		err = e.Orm.Table("sys_shopping_cart").Select("id", "num").Where("deleted_at is null and buyer_id=? and material_online_id=? and order_type=?", req.BuyerId, req.MaterialOnlineId, req.OrderType).Scan(&inum).Error
		if err != nil {
			e.Logger.Error("db error:", err)
		}
		if inum.Num >= 1 { //存在,更新
			err := e.Orm.Table("sys_shopping_cart").Where("id=?", inum.Id).Update("num", inum.Num+1).Error
			if err != nil {
				e.Logger.Error("db error:", err)
				return
			}

		} else {

			var object modelsadmin.SysCourse
			sa := serviceadmin.SysCourse{}
			sa.Orm = s.Orm
			reqa := dtoadmin.SysCourseById{}
			reqa.Id = req.MaterialOnlineId
			//数据权限检查
			p := actions.GetPermissionFromContext(c)
			err = sa.Get(&reqa, p, &object)
			if err != nil {
				e.Error(http.StatusUnprocessableEntity, err, "查询失败")
				return
			}
			orderType := "OnlineOrder"
			if object.CourseType == "live" {
				orderType = "LiveOrder"
			}
			err = s.Insert(&req, object.Name, object.Subject, object.Introduction, orderType, object.Cover, object.Price)
			if err != nil {
				e.Logger.Error(err)
				e.Error(500, err, err.Error())
				return
			}
		}
	default:
		e.OK(req.GetId(), "OrderType err")
	}

	e.OK(req.GetId(), "创建成功")
}

func (e ApiShoppingCart) Change(c *gin.Context) {
	s := service.SysShoppingCart{}
	req := dto.SysShoppingCartUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

func (e ApiShoppingCart) Delete(c *gin.Context) {
	s := new(service.SysShoppingCart)
	req := dto.SysShoppingCartDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, fmt.Sprintf("删除角色 %v 失败，\r\n失败信息 %s", req.Id, err.Error()))
		return
	}
	if len(req.Ids) > 0 {
		for _, ids := range req.Ids {
			req := dto.SysShoppingCartDeleteReq{}
			req.Id = ids
			err = s.Remove(&req)
			if err != nil {
				e.Logger.Error(err)
				e.Error(500, err, "")
				return
			}
		}
		_, err = global.LoadPolicy(c)
		if err != nil {
			e.Error(500, err, fmt.Sprintf("删除角色 %v 失败，失败信息 %s", req.GetId(), err.Error()))
			return
		}
		e.OK(req.GetId(), fmt.Sprintf("删除角色角色 %v 状态成功！", req.GetId()))
		return
	}
	xlog.Error("req.Ids len = 0")
	e.OK(req.GetId(), fmt.Sprintf("删除角色角色 %v 状态成功！", req.GetId()))
}
